using Microsoft.Practices.Unity;

namespace UniAspect.ContainerOverride
{
    /// <summary>
    /// Extension to simplify adding and using overrides
    /// </summary>
    public static class ContainerExtension
    {
        public static IUnityContainer CreateOverride(this IUnityContainer container, string overrideName)
        {
            var overridingExtension = container.Configure<OverridingExtension>();
            if(overridingExtension == null)
            {
                overridingExtension = new OverridingExtension();
                container.AddExtension(overridingExtension);
            }
            var overrideContainer = container.CreateChildContainer();
            overridingExtension.AddOverride(overrideContainer, overrideName);
            return overrideContainer;
        }

        public static T Override<T>(this IUnityContainer container, string overrideName)
        {
            return container.Configure<OverridingExtension>()
                    .GetOverride(overrideName)
                    .Resolve<T>();
        }

        public static IUnityContainer GetOverride(this IUnityContainer container, string overrideName)
        {
            return container.Configure<OverridingExtension>()
                    .GetOverride(overrideName);
        }
    }
}